/*
 * @Author: gavin
 * @Date:   2017-12-21 14:57:37
 * @Last Modified by:   gavin
 * @Last Modified time: 2017-12-25 11:10:16
 */
// require('es6-promise').polyfill();
import fetch from 'isomorphic-fetch';
import {
	observable,
	computed,
	action,
	runInAction,
	autorun
} from 'mobx';
import uuid from 'node-uuid';


const config = global.CONFIG.api;
class news {

	@observable data = []
	constructor() {
		// this.data=[];
		// this.init();
		// autorun(()=> console.log(this.data.length));
	}
	@computed get getData() {
		return this.data.slice();
	}
	@action getList = async() => {
		// console.log(JSON.stringify(global.CONFIG));
		const url = 'http://' + config.host + ':' + config.port + '/api/news';
		// console.log(url);
		await fetch(url).then(
				(res) => {
					if (res.status >= 400) {
						throw new Error("Bad response from server");
					}
					return res.json();
				})
			.then((store) => {
				runInAction("获取文章内容", () => {
					// console.log(store.data);
					this.data = store.data;
				});

			}).catch((err) => {
				console.log(err);
			});
	}
}

export default news;
export class Backlogs {
	store = null;
	@observable isLoading = true;

	@observable backlogs = [];

	constructor(store) {
		this.store = store;
		// this.load();
	}

	@computed get asJson() {
		return this.backlogs.slice();
	}
	@action async load() {
		this.isLoading = true;
		const url = 'http://' + config.host + ':' + config.port + '/api/news';
		await fetch(url).then(
				(res) => {
					if (res.status >= 400) {
						throw new Error("Bad response from server");
					}
					return res.json();
				})
			.then((datas) => {
				runInAction("获取文章内容", () => {
					datas.data.forEach(json => this.update(json));
					this.isLoading = false;
				});
			}).catch((err) => {
				console.log(err);
			});
	}
	@action.bound update(json) {
		let data = this.backlogs.find(data => data.id === json.id);
		if (!data) {
			data = new Backlog(this, json.id);
			this.backlogs.push(data);
			// console.log(data);
		}
		if (json.isDeleted) {
			this.removeTodo(data);
		} else {
			data.updateFromJson(json);
		}
	}
	@action.bound create() {
		let data = new Backlog(this);
		this.backlogs.push(data);
		return data;
	}
	@action.bound remove(data) {
		this.backlogs.splice(this.backlogs.indexOf(data), 1);
		data.dispose();
	}
};
export class Backlog {
	autoSave = true;
	saveHandler = null;
	store = null;

	id = null;
	@observable title = "";
	@observable time = "";

	constructor(store, id=uuid.v4()) {
		this.store = store;
		this.id = id;
	}
	@computed get asJson() {
		return {
			id: this.id,
			title: this.title,
			time: this.time
		};
	}
	@action.bound updateFromJson(json) {
		// 请确保我们的更改不会发送回服务器
		this.autoSave = false;
		this.title = json.title;
		this.time = json.time;
		this.autoSave = true;
	}
};
